﻿using System;
using System.Linq;
using System.Windows.Forms;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.DataSourcesRaster;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.SystemUI;
using ICommand = ESRI.ArcGIS.SystemUI.ICommand;

namespace whu2020302051098 {

    public partial class Form1 : Form
    {
        private ILayer pLayer;//定义全局变量pLayer
        private string path1 = Application.StartupPath + "/../../ProjectFile/通用地图数据/武大.mxd";
        private string path2= Application.StartupPath + "/../../ProjectFile/路径分析地图数据/武大.mxd";

        public Form1() {
            
            InitializeComponent();
            //关闭窗口退出整个程序
            this.FormClosing += (sender, args) =>
            {
                Application.Exit();
            };

            axMapControl1.OnMapReplaced += (sender, @event) =>
            {
               
                if (axMapControl1.LayerCount > 0) {
                    for (int i = 0; i < axMapControl1.LayerCount; i++)
                        axMapControl2.AddLayer(axMapControl1.get_Layer(i));
                    axMapControl2.Extent = axMapControl1.FullExtent;    // 初始化时设置鹰眼视图为全局视图
                    
                    //axMapControl2.Map.MapScale = 1/30000.0;
                    axMapControl2.Refresh();	// Extent变化后记得要Refresh
                }
            };

            axMapControl1.LoadMxFile(path1);

            axMapControl2.OnMouseDown += axMapControl2_OnMouseDown;
            axMapControl2.OnMouseMove += axMapControl2_OnMouseMove;
            axMapControl1.OnExtentUpdated += axMapControl1_OnExtentUpdated;


        }
        private void axMapControl2_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e) {
            if (axMapControl1.LayerCount > 0) {
                if (e.button == 1)   // 左键所点击的位置设置为主视图的中心
                {
                    IPoint pPoint = new PointClass();
                    pPoint.PutCoords(e.mapX, e.mapY);
                    axMapControl1.CenterAt(pPoint);
                    axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);	//对所有数据所有范围刷新
                }
                else if (e.button == 2)  // 右键则拉框范围设置为主试图显示范围
                {
                    IEnvelope pEnv = axMapControl2.TrackRectangle();
                    axMapControl1.Extent = pEnv;
                    axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
                }
            }
        }

        private void axMapControl2_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e) {
            if (e.button == 1) {
                IPoint pPoint = new PointClass();
                pPoint.PutCoords(e.mapX, e.mapY);
                axMapControl1.CenterAt(pPoint);
                axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
            }
        }

        private void axMapControl1_OnExtentUpdated(object sender, IMapControlEvents2_OnExtentUpdatedEvent e) {
            // 获取当前地图视图的外包矩形
            IEnvelope pEnvelope = (IEnvelope)e.newEnvelope;
            // 获得GraphicsContainer对象
            IGraphicsContainer pGraphicsContainer = axMapControl2.Map as IGraphicsContainer;

            IActiveView pActiveView = pGraphicsContainer as IActiveView;
            // 清除对象中的所有图形元素
            pGraphicsContainer.DeleteAllElements();

            // 获得矩形图形元素
            IRectangleElement pRectangleEle = new RectangleElementClass();
            IElement pElement = pRectangleEle as IElement;
            pElement.Geometry = pEnvelope;

            //设置FillShapeElement对象的symbol
            IFillShapeElement pFillShapeEle = pElement as IFillShapeElement;
            pFillShapeEle.Symbol = getFillSymbol();
            // 进行填充
            pGraphicsContainer.AddElement((IElement)pFillShapeEle, 0);
            // 刷新试图
            pActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
        }

        /// <summary>
        /// 获得鹰眼视图显示方框的symbol
        /// </summary>
        /// <returns></returns>
        private IFillSymbol getFillSymbol() {
            // 矩形框的边界线颜色
            IRgbColor pColor = new RgbColorClass();
            pColor.Red = 0;
            pColor.Green = 0;
            pColor.Blue = 255;
            pColor.Transparency = 255;
            // 边界线
            ILineSymbol pOutline = new SimpleLineSymbolClass();
            pOutline.Width = 2;
            pOutline.Color = pColor;
            // symbol的背景色
            pColor = new RgbColorClass();
            pColor.Red = 255;
            pColor.Green = 0;
            pColor.Blue = 0;
            pColor.Transparency = 0;
            // 获得显示的图形元素
            IFillSymbol pFillSymbol = new SimpleFillSymbolClass();
            pFillSymbol.Color = pColor;
            pFillSymbol.Outline = pOutline;
            return pFillSymbol;
        }




        private void loadMxdFileToolStripMenuItem_Click(object sender, EventArgs e) {
            OpenFileDialog OpenMXD = new OpenFileDialog();
            OpenMXD.Title = "打开地图";
            OpenMXD.InitialDirectory = "D:\\";
            OpenMXD.Filter = "Map Documents (*.mxd)|*.mxd";
            if (OpenMXD.ShowDialog() == DialogResult.OK) {
                string MxdPath = OpenMXD.FileName;
                axMapControl1.LoadMxFile(MxdPath);
            }

        }

        private void loadVectorFileToolStripMenuItem_Click(object sender, EventArgs e) {
            
            OpenFileDialog xjOpenShpFileDialog = new OpenFileDialog();
            xjOpenShpFileDialog.Title = "打开矢量数据";
            xjOpenShpFileDialog.Filter = "矢量文件(*.shp)|*.shp";

            if (xjOpenShpFileDialog.ShowDialog() == DialogResult.OK) {
                string xjShpPath = xjOpenShpFileDialog.FileName;
                string xjShpFolder = System.IO.Path.GetDirectoryName(xjShpPath);
                string xjShpFileName = System.IO.Path.GetFileName(xjShpPath);
                //工作工厂+工作空间
                IWorkspaceFactory xjShpWsF = new ShapefileWorkspaceFactory();
                IFeatureWorkspace xjShpFWs = (IFeatureWorkspace)xjShpWsF.OpenFromFile(xjShpFolder, 0);
                //新建矢量图层：要素+名称
                IWorkspace xjShpWs = xjShpWsF.OpenFromFile(xjShpFolder, 0);
                IFeatureClass xjShpFeatureClass = xjShpFWs.OpenFeatureClass(xjShpFileName);
                IFeatureLayer xjShpFeatureLayer = new FeatureLayer();
                xjShpFeatureLayer.FeatureClass = xjShpFeatureClass;
                xjShpFeatureLayer.Name = xjShpFeatureClass.AliasName;
                //加载刷新
                axMapControl1.AddLayer(xjShpFeatureLayer);
                axMapControl1.ActiveView.Refresh();
            }
        }

        private void loadRasterFileToolStripMenuItem_Click(object sender, EventArgs e) {
            OpenFileDialog pOpenFileDialog = new OpenFileDialog();
            pOpenFileDialog.CheckFileExists = true;
            pOpenFileDialog.Title = "打开栅格文件";
            pOpenFileDialog.Filter = "栅格文件 (*.*)|*.bmp;*.tif;*.jpg;*.img|(*.bmp)|*.bmp|(*.tif)|*.tif|(*.jpg)|*.jpg|(*.img)|*.img";
            pOpenFileDialog.ShowDialog();

            string pRasterFileName = pOpenFileDialog.FileName;
            if (pRasterFileName == "") {
                return;
            }

            string pPath = System.IO.Path.GetDirectoryName(pRasterFileName);
            string pFileName = System.IO.Path.GetFileName(pRasterFileName);

            IWorkspaceFactory pWorkspaceFactory = new RasterWorkspaceFactory();
            IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(pPath, 0);
            IRasterWorkspace pRasterWorkspace = pWorkspace as IRasterWorkspace;
            IRasterDataset pRasterDataset = pRasterWorkspace.OpenRasterDataset(pFileName);
            //影像金字塔判断与创建
            IRasterPyramid3 pRasPyrmid;
            pRasPyrmid = pRasterDataset as IRasterPyramid3;
            if (pRasPyrmid != null) {
                if (!(pRasPyrmid.Present)) {
                    pRasPyrmid.Create(); //创建金字塔
                }
            }
            IRaster pRaster;
            pRaster = pRasterDataset.CreateDefaultRaster();
            IRasterLayer pRasterLayer;
            pRasterLayer = new RasterLayerClass();
            pRasterLayer.CreateFromRaster(pRaster);
            ILayer pLayer = pRasterLayer as ILayer;
            axMapControl1.AddLayer(pLayer, 0);
        }
        
        private void ClearAllData() {
            if (axMapControl1.Map != null && axMapControl1.Map.LayerCount > 0) {
                //新建mainMapControl中Map
                IMap dataMap = new MapClass();
                dataMap.Name = "Map";
                axMapControl1.DocumentFilename = string.Empty;
                axMapControl1.Map = dataMap;
            }
        }

        private void loaderDataBaseToolStripMenuItem_Click(object sender, EventArgs e) {
            IWorkspaceFactory pFileGDBWorkspaceFactory;

            FolderBrowserDialog dlg = new FolderBrowserDialog();
            if (dlg.ShowDialog() != DialogResult.OK) return;
            string pFullPath = dlg.SelectedPath;

            if (pFullPath == "") {
                return;
            }
            pFileGDBWorkspaceFactory = new FileGDBWorkspaceFactoryClass(); //using ESRI.ArcGIS.DataSourcesGDB;

            ClearAllData();    //新增删除数据

            //获取工作空间
            IWorkspace pWorkspace = pFileGDBWorkspaceFactory.OpenFromFile(pFullPath, 0);
            //AddAllDataset(pWorkspace, KarstCropMap);
        }

        private void axTOCControl1_OnMouseDown(object sender, ESRI.ArcGIS.Controls.ITOCControlEvents_OnMouseDownEvent e) {
            if (axMapControl1.LayerCount > 0) {
                esriTOCControlItem pItem = new esriTOCControlItem();//用类实例化         
                pLayer = new FeatureLayerClass();
                IBasicMap pBasicMap = new MapClass();
                object pOther = new object();
                object pIndex = new object();
                // Returns the item in the TOCControl at the specified coordinates.
                axTOCControl1.HitTest(e.x, e.y, ref pItem, ref pBasicMap, ref pLayer, ref pOther, ref pIndex);
            }//TOCControl类的ITOCControl接口的HitTest方法,获取坐标（下一页解释）
            if (e.button == 2)//等待点击右键
            {
                contextMenuStrip1.Show(axTOCControl1, e.x, e.y);//显示菜单项
            }
        }

        private void openAttributeTableToolStripMenuItem_Click(object sender, EventArgs e) {
            AttributeTable attribute = new AttributeTable(pLayer as IFeatureLayer);
            attribute.Show();
        }

        private void attributeQueryToolStripMenuItem_Click(object sender, EventArgs e) {

            QueryAttrForm form = new QueryAttrForm(this.axMapControl1);
            form.Show();

        }

        private void addStopsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ICommand pCommand;
            pCommand = new AddNetStopsTool();
            pCommand.OnCreate(this.axMapControl1.Object);
            axMapControl1.CurrentTool = pCommand as ITool;
        }

        private void infrastructureQueryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            InfrastructureQueryForm infrastructureQueryForm = new InfrastructureQueryForm(this.axMapControl1);
            infrastructureQueryForm.Show();
        }

        private void attractionIntroToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AttractionIntroForm form = new AttractionIntroForm(this.axMapControl1);
            form.Show();
        }

        private void enterRegisterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RegisterForm form = new RegisterForm();
            form.Show();
        }

        private void setStopToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ControlsNetworkAnalystCreateLocationToolClass CreateLocationToolCmd = new ControlsNetworkAnalystCreateLocationToolClass();
            CreateLocationToolCmd.OnCreate(axMapControl1.Object);
            CreateLocationToolCmd.OnClick();
            this.axMapControl1.CurrentTool = CreateLocationToolCmd as ITool;
        }

        private void excecuteAnalyseToolStripMenuItem_Click(object sender, EventArgs e) {
            ControlsNetworkAnalystSolveCommandClass networkAnalystCmd = new ControlsNetworkAnalystSolveCommandClass();
            networkAnalystCmd.OnCreate(axMapControl1.Object);
            networkAnalystCmd.OnClick();
            this.axMapControl1.CurrentTool = networkAnalystCmd as ITool;
        }

        private void loadNetToolStripMenuItem_Click(object sender, EventArgs e) {
            axMapControl1.LoadMxFile(path2);
        }

        private void clearNetToolStripMenuItem_Click(object sender, EventArgs e) {
            axMapControl1.LoadMxFile(path1);
        }




    }
}
